

import 'package:alip_app/Entities/SignInResult.dart';
import 'package:alip_app/StateManagement/ModelProvider.dart';
import 'package:flutter/cupertino.dart';
import 'package:shared_preferences/shared_preferences.dart';

import '../HttpInterface.dart';
import 'NetworkApi.dart';
import '';

class UserState extends Model {
  SignInResult userInfo;
  get hasSignIn => this.userInfo != null;
  Widget ensureHasSignIn({BuildContext context, Widget child, void signInAction()}) {
    if (this.hasSignIn) return CupertinoAlertDialog(
      title: Text("بۇ يەردە بىر مەسىلە مەۋجۇت"),
      content: Text("ئاۋال ھىساباتىڭىز بىلەن تىزىملاپ كىرىڭ"),
      actions: [
        CupertinoButton(child: Text("ماقۇل"), onPressed: signInAction)
      ],
    );
    else return child;
  }
  Future<SignInResult> signIn(BuildContext context, SignInMode signInMode) async {
    final api = ModelContainer.of<NetworkApi>(context).model.api;
    final result = await api.signIn(signInMode);
    await _rememberPassword(signInMode);
    this.userInfo = result;
    this.applyChanges();
    return result;
  }
  Future<void> _rememberPassword(WithPassword accountInformation) async {
    final preferences = await SharedPreferences.getInstance();
    await preferences.setString("userName", accountInformation.userName);
    await preferences.setString("password", accountInformation.password);
  }
  Future<WithPassword> getRememberedAccount() async {
    final preferences = await SharedPreferences.getInstance();
    final userName = preferences.getString("userName");
    final password = preferences.getString("password");
    if (userName == null) return null;
    return WithPassword(
      userName: userName,
      password: password,
    );
  }
}
